const Com = require("../gmoon/baseCom");
const STATE = require("../states/gunstates");
cc.Class({
    extends: Com,

    properties: {
    },

    ctor(){
        this._lev = 0;
        this.setState( STATE.READY );
    },

    onLoad(){
        //绑定拖拽
        this.bindDrag({
            start : {
                handler : this.onTouchStartEvent.bind(this) ,
                check : this.checkTouchStart.bind(this)
            },
            move : { handler : this.onTouchMoveEvent.bind(this) },
            end : { handler : this.onTouchEndEvent.bind(this) },
            cancel : { handler : this.onTouchCancelEvent.bind(this) }
        });
        //this.node.opacity = 1;
        this.node.zIndex = 10;
        this.setAttr("_gid" , $T.timestamp() );

        //自动发射绑定
        this.appendHookHandler( "update" , this.OnAutoShoot.bind(this));
    },

    flymodel( flg ){
        flg = $T.selectValue( flg , true );

        if(flg){
            cc.tween( this.node )
            .by(.5 , {y:50})
            .call(()=>{
                this.childNode("fly").active = flg;
                $Animate.do("playPop" ,  this.childNode("fly"));
                this.setAttr("_flymodel" , flg);
            })
            .start();
        }else{
            
            cc.tween( this.childNode("fly") )
            .by(.1 , { scale : 0})
            .call(()=>{
                this.childNode("fly").active = flg;
                this.setAttr("_flymodel" , flg);
            })
            .start();
        }
    },

    onTouchStartEvent(e){
        let p = e ? e.getUserData() : {};
        $EBUS.emit("gun-start-evnet" , p );
        this._readyMove();
    },

    onTouchMoveEvent(e){
        let p = e ? e.getUserData() : {};
        const curpos = cc.v2(p.pos.x , p.pos.y);
        this.node.setPosition( curpos );
        //
        p.callback = ( pback )=>{
            //console.log('callback');
        }
        $EBUS.emit("gun-moving-evnet" , p );
    },

    onTouchEndEvent(e){
        let p = e ? e.getUserData() : {};
        p.callback = ( flag )=>{
            if(!flag) this._resumePos();
        }
        this.resumeLastState();
        this.node.zIndex = 10;
        $EBUS.emit("gun-moving-end-evet" , p);
    },

    onTouchCancelEvent( e ){
        let p = e.getUserData();
        //this._resumePos();
        p.callback = ( flag )=>{
            if(!flag) this._resumePos();
        }
        this.resumeLastState();
        this.node.zIndex = 10;
        $EBUS.emit("gun-moving-end-evet" , p);
    },

    checkTouchStart(){
        return !( this.isState(STATE.BACKING) || this.isState(STATE.MOVE))
    },
    
    _readyMove(){
        //const pool = $G.get("pool-zidan");
        this.setState( STATE.MOVEING );
        this.setAttr("_slefPos" , this.node.getPosition());
        this.node.zIndex = 30;
        let rezidan = this.getAttr("_ready_zidan");
        if(rezidan){
            //rezidan.active = false;
            for(let i in rezidan){
                rezidan[i] &&  $T.getScr(rezidan[i]).unuse() && $G.do('poolPutByNode' , 'put' , rezidan[i])  //pool.put(rezidan);
            }
        }
    },

    _resumePos(){
        let fly =  this.childNode("fly");
        if(!fly.active){
            let father = this.getAttr("_father");
            let topos = father.node.parent.convertToWorldSpaceAR(father.node.getPosition());
            //let torotation = $T.getAngle( this.node.convertToNodeSpaceAR(topos) );
            topos = this.node.parent.convertToNodeSpaceAR(topos)
            
            cc.tween( this.node )
            .to(.2 , {x : topos.x , y: topos.y} )
            .call(()=>{
                father.fitGun( this.node );
            })
            .start();

        }else if(this.getAttr("_father")){
            let father = this.getAttr("_father");
            let topos = father.node.parent.convertToWorldSpaceAR(father.node.getPosition());
            //let torotation = $T.getAngle( this.node.convertToNodeSpaceAR(topos) );
            topos = this.node.parent.convertToNodeSpaceAR(topos)
            cc.tween( this.node )
            .call(()=>{
                //标识正在返回;
                this.setState(STATE.BACKING);
            })
            .to( .3 , {scale : .9 })
            .to(1 , {x : topos.x , y: topos.y} )
            .call(()=>{
                father.fitGun( this.node );
            })
            .start();

        }
    },

    setSize( w , h){
        return $T.setNodeSize(this.node ,[w,h]);
    },

    //当状态发生变化后 , 自动执行
    onStateChanged( frmState , toState ){
        if( this.isState(STATE.INHEBING) ){
            this.childNode("sprite").rotation = 0;
            cc.tween( this.node )
            .to( .05 , {rotation:35})
            .start();
        }else if( this.isState(STATE.INPAOTAI) ){
            this.childNode("sprite").rotation = 0;
            this.node.rotation = 0;
            // cc.tween( this.node )
            // .to( .05 , {rotation:0})
            // .start();
        }else if( this.isState(STATE.MOVEING) ){
            this.childNode("sprite").rotation = 0;
            this.node.rotation = 0;
            // cc.tween( this.node )
            // .to( .05 , {rotation:0})
            // .start();
        }else if( this.isState(STATE.HEBING) ){
            this.childNode("sprite").rotation = 0;
            this.node.rotation = 0;
        }
    },

    //设置lev
    setLevel( lev ){
        lev = lev || 1;
        return this;
    },

    getInfo(){
        return {
            killv : 50
        }
    },

    //射击 
    shoot( tonodepos , lev ){
        const conf = { //INBIGHEBING
            num : this.isState(STATE.MOVEING) ? 7 : ( this.isState(STATE.INBIGHEBING)? 1 : 2 ),
            killv : 50,
            type : this.isState(STATE.MOVEING) ? 'smzidan' : ( this.isState(STATE.INBIGHEBING)? 'zidan' : "zidan" ),
            size : this.isState(STATE.MOVEING) ? [30,] : null,
            sprite : this.isState(STATE.INBIGHEBING)? this.node : this.childNode("sprite"),
            time : this.isState(STATE.INBIGHEBING)? .2 : .13
        }

        let rotation = 90-$T.getAngle( this.node.convertToNodeSpaceAR(tonodepos) );
        cc.tween( conf.sprite )
        .to( conf.time , { rotation : rotation } , {easing:"backOut"} )
        .call(()=>{
            let zidans = (()=>{
                let num = conf.num || 1 , re = [] , tz;
                for(let i=0; i<num; i++){
                    tz = $G.get("poolGetByName" , conf.type) || $RES.createPrefab("fab-" + conf.type);
                    conf.size && $T.setNodeSize(tz , conf.size);
                    re.push( tz );
                }
                
                return re;
            })()

            this.setAttr("_ready_zidan" , zidans );
            this._shootZidan( zidans , rotation , tonodepos);
        })
        .start();
    },

    _shootZidan( arr , rotation , topos ){
        arr = arr || [];
        const anima = this.childNode("sprite > gunanim");
        let pos = this.node.convertToNodeSpaceAR(topos);
        let selfInfo = this.getInfo();

        const angles = (()=>{
            let re = [] , jg=3;
            for(let i=0; i<arr.length; i++){
                re.push( $T.compListPoxV( 0 , i , jg , arr.length ) )
            }

            return re;
        })();

        let go = ( i )=>{
            if(i>=arr.length) return;
            let zidan = arr[i];
            let zdy = this.node.height * .8;
            let zdrota = $T.getAngle( pos ),
                zdpos = cc.v2( zdy*Math.cos( $T.toRota( zdrota )) , zdy*Math.sin( $T.toRota( zdrota ) )) ;

            zidan.scale = 0;
            zidan.parent = this.node;
            zidan.active = true;
            zidan.setPosition( zdpos );
            zidan.rotation = angles[i] + rotation;
            $T.getScr(zidan).setInfo({
                killv : selfInfo.killv/arr.length * (arr.length>1?arr.length/2:2)
            });

            cc.tween( zidan )
            .to(.2 , {scale:1})
            .call(()=>{
                
                cc.tween(anima)
                .to( .05 , {opacity : 255} )
                .call(()=>{
                    anima.getComponent(cc.Animation).play("gun");
                }).delay(.2).call(()=>{
                    anima.opacity = 0;
                }).start();

                if( zidan && zidan.parent ){
                    $T.getScr(zidan).reuse().emit();
                }else{
                    $T.getScr(zidan).unuse() && $G.do('poolPutByNode' , 'put' , zidan);  //pool.put(zidan);
                }
                this.setAttr("_ready_zidan" , null );
            })
            .start();

            go( i+1 );
        }

        go(0);
        setTimeout(() => {
            $RES.playVoice("sound-shoot");
        }, 200);
    },

    _flyringUpdate( dt ){
        const fly = this.childNode("fly");
        if(!this.childNode("fly").active) return;
        const leftlx = $T.findChildNode(" flyleft > fly1-lx" , fly ),
              rightlx =  $T.findChildNode(" flyright > fly1-lx" , fly );
        
        let rota = leftlx.rotation;
        rota -= dt*500;
        rota = rota>360 ? rota-360 : rota;
        rota = rota<-360 ? 360+rota : rota;
        leftlx.rotation = rota;

        rota = rightlx.rotation;
        rota -= dt*500;
        rota = rota>360 ? rota-360 : rota;
        rota = rota<-360 ? 360+rota : rota;

        rightlx.rotation = rota;
    },

    OnAutoShoot( dt ){
        if(!$G.get("running")) return;
        
        let viruspanel = $G.get("viruspanel");
        //时间累加器
        let acc = this.getAttr("acc");
        this.setAttr("acc" , ( acc ? acc : 0 ) + dt );

        //螺旋将旋转
        this._flyringUpdate( dt );

        if(this.getAttr("acc")>=1 && this.isState(STATE.INPAOTAI)){
            let toNode = viruspanel.get(1 , "most");
            if(toNode){
                this.shoot( toNode.parent.convertToWorldSpaceAR(toNode.getPosition()) );
                this.setAttr("acc" , 0.0 );
            }else{
                console.log("no node")
            };
        }else if( this.isState(STATE.MOVEING) && this.getAttr("_flymodel") && Math.floor(this.getAttr("acc")*10) % 3 == 0 ){

            this.shoot( this.node.parent.convertToWorldSpaceAR( this.node.getPosition().add(cc.v2(0,1000) ) ) );
            this.setAttr("acc" , 0.1 );

        }else if( this.isState(STATE.INBIGHEBING) && Math.floor(this.getAttr("acc")*10) % 10 == 0  ){
            let father = this.getAttr("_father");
            if( this.childNode("fly").active){
                
            }

            // let toNode = viruspanel.get(1 , "most");
            // this.shoot( toNode.parent.convertToWorldSpaceAR(toNode.getPosition()) );
            // this.setAttr("acc" , 0.1 );
        }else if( this.isState(STATE.BACKING) ){
            let father = this.getAttr("_father");
            let topos = father.node.parent.convertToWorldSpaceAR(father.node.getPosition());
            let torotation = $T.getAngle( this.node.convertToNodeSpaceAR(topos) );
            topos = this.node.parent.convertToNodeSpaceAR(topos)
        }
    },
    
    update (dt) {
        this._super( dt );
    },
});
